#include <stdlib.h>

#include <windows.h>

#include "casbase.h"

#define INIFILE	"server.ini"
#define USRFILE	"users.ini" // CSN-8334 - Move USERS stats out of server.ini
#define USRSTAT	"USERS"

char CasinoBase::basename[20] = { 0 };
int32 CasinoBase::baseport = 0;

void 
CasinoBase::load()
{
	char inifile[MAX_PATH + 1];
	int32 len;

	len = GetModuleFileName(NULL, inifile, MAX_PATH);
	while (len && inifile[len - 1] != '\\')
		len--;
	lstrcpy(inifile + len, INIFILE);

	getStrOpt("Base", "name", "", basename, 20, inifile);
	baseport = getInt32Opt("Base", "port", 0, inifile);
}
  
void
CasinoBase::getStrOpt(char* Section, char* Key, char* Default,
	char* Dest, int32 MaxDest, char* IniFile)
{
	int32 len;

	len = GetPrivateProfileString(Section, Key, Default,
		Dest, MaxDest - 1, IniFile);
	len = strip(Dest, len);
	Dest[len] = '\0';
}

void
CasinoBase::getStrOptEx(char* Section, char* Key, char* Default,
	char* Dest, int32 MaxDest)
{

    char inifile[MAX_PATH + 1];
	int32 len;

	len = GetModuleFileName(NULL, inifile, MAX_PATH);
	while (len && inifile[len - 1] != '\\')
		len--;
	
	// CSN-8334 - Move USERS stats out of server.ini
	lstrcpy(inifile + len, (lstrcmp(Key, USRSTAT)) ? INIFILE : USRFILE);

	len = GetPrivateProfileString(Section, Key, Default,
		Dest, MaxDest - 1, inifile);
	len = strip(Dest, len);
	Dest[len] = '\0';
}
 
int32
CasinoBase::getInt32Opt(char* Section, char* Key, int32 Default, char* IniFile)
{
	return (int32)GetPrivateProfileInt(Section, Key, (INT)Default, IniFile);
}

int32
CasinoBase::getInt32OptEx(char* Section, char* Key, int32 Default)
{
	char inifile[MAX_PATH + 1];
	int32 len;

	len = GetModuleFileName(NULL, inifile, MAX_PATH);
	while (len && inifile[len - 1] != '\\')
		len--;
	lstrcpy(inifile + len, INIFILE);

	return (int32)GetPrivateProfileInt(Section, Key, (INT)Default, inifile);
}

int32
CasinoBase::strip(char* buf, int32 len)
{
	char *s, *e;

	if (len <= 0)
		return 0;

	s = buf;
	while (len > 0 &&
		(*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
	{
		++s;
		--len;
	}

	e = s + len - 1;
	while (e > s &&
		(*e == ' ' || *e == '\t' || *e == '\n' || *e == '\r'))
	{
		--e;
		--len;
	}

	s[len] = '\0';

	if (len && s > buf)
		memmove(buf, s, len);

	return len;
}

int
CasinoBase::setStrOptEx(char* Section, char*  Key, char*  Dest)
{
	int bRet;

	char inifile[MAX_PATH + 1];
	int32 len;

	len = GetModuleFileName(NULL, inifile, MAX_PATH);
	while (len && inifile[len - 1] != '\\')
		len--;
	
	// CSN-8334 - Move USERS stats out of server.ini
	lstrcpy(inifile + len, (lstrcmp(Key, USRSTAT)) ? INIFILE : USRFILE);
   
    bRet = WritePrivateProfileString(Section, Key,Dest, inifile);
	return bRet;
}
